﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace FinMkts.Messaging.Pgm
{
    public class ByteBufferCollection : Collection<ArraySegment<byte>>
    {
        private int _totalBytes;

        public int TotalBytes
        {
            get { return _totalBytes; }
        }

        protected override void InsertItem(int index, ArraySegment<byte> item)
        {
            base.InsertItem(index, item);
            _totalBytes += item.Count;
        }

        protected override void ClearItems()
        {
            base.ClearItems();
            _totalBytes = 0;
        }

        protected override void RemoveItem(int index)
        {
            var oldItem = Items[index];
            base.RemoveItem(index);
            _totalBytes -= oldItem.Count;
        }

        protected override void SetItem(int index, ArraySegment<byte> item)
        {
            var oldItem = Items[index];
            _totalBytes -= oldItem.Count;
            base.SetItem(index, item);
            _totalBytes += item.Count;
        }

        public void AddRange(IEnumerable<byte[]> items)
        {
            if (items == null) throw new ArgumentNullException("items");
            foreach (var item in items)
            {
                Add(new ArraySegment<byte>(item));
            }
        }
    }
}
